package com.itheima.aimobile.config;

import com.itheima.aimobile.domain.SystemConstants;
import com.itheima.aimobile.tool.MyTool;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.vectorstore.QuestionAnswerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiEmbeddingModel;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CommConfig {
    // embeddingModel向量数据库，目前保存到内存中
    @Bean
    public VectorStore vectorStore(OpenAiEmbeddingModel embeddingModel) {
        return SimpleVectorStore.builder(embeddingModel).build();//内存
    }

    // jsonChatClient json知识库,然后调用接口进行问答
    @Bean
    public ChatClient jsonChatClient(OpenAiChatModel servicechatModel,
                                     ChatMemory chatMemory,
                                     VectorStore vectorStore,
                                     MyTool myTool){
        return ChatClient.builder(servicechatModel)
                .defaultSystem(SystemConstants.CUSTOMER_SERVICE_SYSTEM)
                .defaultTools(myTool)
                .defaultAdvisors(new SimpleLoggerAdvisor()) // 添加默认的Advisor,记录日志
                .defaultAdvisors(MessageChatMemoryAdvisor.builder(chatMemory).build())// 添加默认的Advisor,持久化存储
                .defaultAdvisors(QuestionAnswerAdvisor.builder(vectorStore)
                        .searchRequest(SearchRequest.builder() // 向量检索的请求参数
                                .similarityThreshold(0.6) // 相似度阈值
                                .topK(2) // 返回的文档片段数量
                                .build())
                        .build())

                .build();


    }


}